﻿using System.Linq;
using System.Web.Mvc;
using SacNetUG.Models;

namespace SacNetUG.Controllers
{
    public partial class ContentController : Controller
    {
        public virtual ActionResult Index()
        {
            return View();
        }

        public virtual ActionResult Detail(string controllerToView, string actionToView)
        {
            var db = new SacNetUGDataContext();

            return View(db.Contents.FirstOrDefault(p => p.Controller == controllerToView && p.Action == actionToView));
        }

        [Authorize]
        public virtual ActionResult Create(string controllerToEdit, string actionToEdit)
        {
            return View(new Content {Controller = controllerToEdit, Action = actionToEdit});
        }

        [HttpPost]
        [ValidateInput(false), Authorize]
        public virtual ActionResult Create(Content content)
        {
            try
            {
                content.SanitizeInput();

                if (!ModelState.IsValid)
                    return View(content);

                var db = new SacNetUGDataContext();
                db.Contents.InsertOnSubmit(content);
                db.SubmitChanges();

                SetCmsRoutes();

                return RedirectToAction(content.Action, content.Controller);
            }
            catch
            {
                return View();
            }
        }

        [Authorize]
        public virtual ActionResult Edit(string controllerToEdit, string actionToEdit)
        {
            var db = new SacNetUGDataContext();

            Content content =
                db.Contents.FirstOrDefault(c => c.Controller == controllerToEdit && c.Action == actionToEdit);

            return content == null ? Create(controllerToEdit, actionToEdit) : View(content);
        }

        [HttpPost]
        [ValidateInput(false), Authorize]
        public virtual ActionResult Edit(int id, Content content)
        {
            try
            {
                content.SanitizeInput();

                if (!ModelState.IsValid)
                    return View(content);

                var db = new SacNetUGDataContext();
                UpdateModel(
                    db.Contents.FirstOrDefault(c => c.Controller == content.Controller && c.Action == content.Action));
                db.SubmitChanges();

                SetCmsRoutes();

                return RedirectToAction(content.Action, content.Controller);
            }
            catch
            {
                return View(content);
            }
        }

        private static void SetCmsRoutes()
        {
            MvcApplication.RoutesLoaded = true;

            var db = new SacNetUGRepository();
            MvcApplication.CmsRoutes = db.GetCmsRoutes();
        }
    }
}